package cn.hongxin.sap.conn.controller;

import cn.getech.poros.framework.common.api.RestResponse;
import cn.getech.poros.framework.common.constants.CommonConstants;
import cn.hongxin.basic.business.client.CommonQueryClient;
import cn.hongxin.basic.business.client.erp.BaErpFunctionClient;
import cn.hongxin.basic.business.client.erp.BaErpFunctionImportClient;
import cn.hongxin.sap.conn.dto.ErpFunctionParamDTO;
import cn.hongxin.sap.conn.dto.ErpFunctionReturnDto;
import cn.hongxin.sap.conn.entity.ErpFunctionReturnVO;
import cn.hongxin.sap.conn.entity.ParamEntity;
import cn.hongxin.sap.conn.utils.MultiFromSAP;
import cn.hongxin.sap.conn.utils.SAPConnUtils;
import cn.hongxin.sap.conn.utils.SapCommHelp;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/sap")
public class SapController {

    @Autowired
    private CommonQueryClient commonQueryClient;

    @Autowired
    private SapCommHelp commHelp;

    @Autowired
    private BaErpFunctionClient baErpFunctionClient;

    @Autowired
    private BaErpFunctionImportClient baErpFunctionImportClient;

    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 解决Redis乱码问题
     * @param redisTemplate
     */
    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        // redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        //redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    /**
     *
     * @param connectMap   SAP连接对象
     * @return
     */
    @GetMapping(value = "/testConnect")
    @ApiOperation(value="SAP连接测试", notes="SAP连接测试", tags = CommonConstants.FEIGN_API_TAG)
    public RestResponse testConnect(@RequestParam String connectMap){
        String connectResult = "";
        try{
            Map map = JSON.parseObject(connectMap);
            if(map!=null && map.size()>0){
                String propertiesName = "ABAP_AS_"+map.get("id");
                connectResult = SAPConnUtils.connecting(propertiesName, map);
            }
            if("success".equals(connectResult)){
                return RestResponse.ok();
            }else{
                return RestResponse.failed();
            }
        }catch (Exception e){
            return RestResponse.failed(e.getMessage());
        }
    }

    /**
     *
     * @param functionName    SAP接口名称
     * @return
     */
    @GetMapping(value = "/getSapParamInfo")
    @ApiOperation(value="SAP接口参数信息获取", notes="SAP接口参数信息获取", tags = CommonConstants.FEIGN_API_TAG)
    public RestResponse getSapParamInfo(@RequestParam String functionName){
        MultiFromSAP multiFromSAP =new MultiFromSAP();
        ParamEntity paramEntity = multiFromSAP.getParamEntity(functionName, baErpFunctionClient, redisTemplate);
        return RestResponse.ok(paramEntity);
    }

    /**
     *
     * @param functionName    SAP接口名称
     * @return
     */
//    @GetMapping(value = "/")
    @RequestMapping(value = "/initFunction",method = RequestMethod.POST)
    @ApiOperation(value="SAP接口参数信息初始化", notes="SAP接口参数信息初始化", tags = CommonConstants.FEIGN_API_TAG)
    public RestResponse initFunction(@RequestParam String functionName){
        ErpFunctionReturnVO erpFunctionReturnVO = null;
        ErpFunctionReturnDto erpFunctionReturnDto = new ErpFunctionReturnDto();
        try{
            MultiFromSAP multiFromSAP =new MultiFromSAP();
            ParamEntity paramEntity = multiFromSAP.getParamEntity(functionName, baErpFunctionClient, redisTemplate);
            String functionId = String.valueOf(paramEntity.getFunctionMap().get("functionid"));
            erpFunctionReturnVO = multiFromSAP.initFunction(functionName, "", commHelp,paramEntity,baErpFunctionClient,baErpFunctionImportClient,redisTemplate);
            BeanUtils.copyProperties(erpFunctionReturnVO,erpFunctionReturnDto);
            //通过当前调用SAP接口定义为手动调用，operatetype=manual，将调用信息手动写入到调用日志表中
            commHelp.insertProdQueue(erpFunctionReturnVO,baErpFunctionClient,functionName,"","");

            return RestResponse.ok(erpFunctionReturnDto);
        }catch (Exception e){
            System.out.println(e.getMessage());
            erpFunctionReturnDto.setReturnErr(e.getMessage());
            return RestResponse.failed(erpFunctionReturnDto);
        }
    }

    /**
     *
     * @param functionName    SAP接口名称
     * @param paramJsonStr  调用参数
     * @return
     */
    @RequestMapping(value = "/callSapInterface",method = RequestMethod.POST)
    @ApiOperation(value="SAP接口调用", notes="SAP接口调用", tags = CommonConstants.FEIGN_API_TAG)
    public RestResponse callSapInterface(@RequestParam String functionName, @RequestParam String paramJsonStr){
        ErpFunctionReturnVO erpFunctionReturnVO = null;
        ErpFunctionReturnDto erpFunctionReturnDto = new ErpFunctionReturnDto();
        try{
            MultiFromSAP multiFromSAP =new MultiFromSAP();
            ParamEntity paramEntity = multiFromSAP.getParamEntity(functionName, baErpFunctionClient, redisTemplate);
            String functionId = String.valueOf(paramEntity.getFunctionMap().get("functionid"));
            erpFunctionReturnVO = multiFromSAP.callSapRfc(functionId, paramJsonStr, commHelp,paramEntity,baErpFunctionClient,redisTemplate);
            BeanUtils.copyProperties(erpFunctionReturnVO,erpFunctionReturnDto);
            //通过当前调用SAP接口定义为手动调用，operatetype=manual，将调用信息手动写入到调用日志表中
            commHelp.insertProdQueue(erpFunctionReturnVO,baErpFunctionClient,functionId,paramJsonStr,"");

            return RestResponse.ok(erpFunctionReturnDto);
        }catch (Exception e){
            System.out.println(e.getMessage());
            erpFunctionReturnDto.setReturnErr(e.getMessage());
           return RestResponse.failed(erpFunctionReturnDto);
        }
    }

    /**
     *
     * @param functionName    SAP接口名称
     * @param paramJsonStr  调用参数
     * @param prodQueueId   参数队列表主键
     * @return
     */
    @RequestMapping(value = "/retryCallSapInterface",method = RequestMethod.POST)
    @ApiOperation(value="SAP接口调用-重试", notes="SAP接口调用-重试", tags = CommonConstants.FEIGN_API_TAG)
    public RestResponse retryCallSapInterface(@RequestParam String functionName, @RequestParam String paramJsonStr,@RequestParam String prodQueueId){
        ErpFunctionReturnVO erpFunctionReturnVO = null;
        ErpFunctionReturnDto erpFunctionReturnDto = new ErpFunctionReturnDto();
        try{
            MultiFromSAP multiFromSAP =new MultiFromSAP();
            ParamEntity paramEntity = multiFromSAP.getParamEntity(functionName + "", baErpFunctionClient, redisTemplate);
            String functionId = paramEntity.getFunctionMap().get("functionid")+"";
            erpFunctionReturnVO = multiFromSAP.callSapRfc(functionId, paramJsonStr, commHelp,paramEntity,baErpFunctionClient,redisTemplate);
            BeanUtils.copyProperties(erpFunctionReturnVO,erpFunctionReturnDto);
            //通过当前调用SAP接口定义为手动调用，operatetype=manual，将调用信息手动写入到调用日志表中
            commHelp.insertProdQueue(erpFunctionReturnVO,baErpFunctionClient,functionId,paramJsonStr,prodQueueId);

            return RestResponse.ok(erpFunctionReturnDto);
        }catch (Exception e){
            System.out.println(e.getMessage());
            erpFunctionReturnDto.setReturnErr(e.getMessage());
            return RestResponse.failed(erpFunctionReturnDto);
        }
    }

    /**
     *
     * @param erpFunctionParamDTO    SAP接口名称
     * @param erpFunctionParamDTO  调用参数
     * @return
     */
    @RequestMapping(value = "/v1/callSapInterface",method = RequestMethod.POST)
    @ApiOperation(value="SAP接口调用(v1版本)", notes="SAP接口调用(v1版本)", tags = CommonConstants.FEIGN_API_TAG)
    public RestResponse invokingSapInterface(@RequestBody ErpFunctionParamDTO erpFunctionParamDTO){
        ErpFunctionReturnVO erpFunctionReturnVO = null;
        ErpFunctionReturnDto erpFunctionReturnDto = new ErpFunctionReturnDto();
        try{
//            MultiFromSAPBak multiFromSAPBak =new MultiFromSAPBak();
            MultiFromSAP multiFromSAP =new MultiFromSAP();
            ParamEntity paramEntity = multiFromSAP.getParamEntity(erpFunctionParamDTO.getFunctionName() + "", baErpFunctionClient, redisTemplate);
//            ParamEntity paramEntity = multiFromSAPBak.getParamEntity(erpFunctionParamDTO.getFunctionName(), baErpFunctionClient, redisTemplate);
            String functionId =String.valueOf(paramEntity.getFunctionMap().get("functionid"));
            erpFunctionReturnVO = multiFromSAP.callSapRfc(functionId, erpFunctionParamDTO.getParamJson(), commHelp,paramEntity,baErpFunctionClient,redisTemplate);
            BeanUtils.copyProperties(erpFunctionReturnVO,erpFunctionReturnDto);
            //通过当前调用SAP接口定义为手动调用，operatetype=manual，将调用信息手动写入到调用日志表中
            commHelp.insertProdQueue(erpFunctionReturnVO,baErpFunctionClient,functionId,JSON.toJSONString(erpFunctionParamDTO.getParamJson()),"");

            return RestResponse.ok(erpFunctionReturnDto);
        }catch (Exception e){
            System.out.println(e.getMessage());
            erpFunctionReturnDto.setReturnErr(e.getMessage());
            return RestResponse.failed(erpFunctionReturnDto);
        }
    }
}
